package top.ochiamalu.aioj.disruptor;

import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.ochiamalu.aioj.constant.JudgeMessageConstants;
import top.ochiamalu.aioj.enums.QuestionTypeEnum;
import top.ochiamalu.aioj.service.JudgeService;
import top.ochiamalu.aioj.websocket.JudgeHandler;

import javax.annotation.Resource;

/**
 * 判题事件处理程序
 *
 * @author ochiamalu
 * @date 2025/01/23
 */
@Slf4j
@Component
public class JudgeEventHandler implements EventHandler<JudgeEvent> {

    @Resource
    private JudgeService judgeService;

    /**
     * 收到判题消息
     *
     * @param event      事件
     * @param sequence   序列
     * @param endOfBatch 批次结束
     */
    @Override
    public void onEvent(JudgeEvent event, long sequence, boolean endOfBatch) {
        String submissionId = event.getJudgeDTO().getSubmissionId();
        try {
            // 发送正在判题状态
            JudgeHandler.sendJudgeStatus(submissionId, JudgeMessageConstants.RUNNING);

            if (event.getJudgeDTO().getQuestionType().equals(QuestionTypeEnum.PROGRAMMING.getCode())){
                // 执行判题
                judgeService.judgeCode(event.getJudgeDTO(), submissionId);
            }

            if (event.getJudgeDTO().getQuestionType().equals(QuestionTypeEnum.MULTIPLE_CHOICE.getCode())){
                judgeService.judgeChoice(event.getJudgeDTO(), submissionId);
            }

            if (event.getJudgeDTO().getQuestionType().equals(QuestionTypeEnum.JUDGEMENT.getCode())){
                judgeService.judgeJudgement(event.getJudgeDTO(), submissionId);
            }
            if (event.getJudgeDTO().getQuestionType().equals(QuestionTypeEnum.FILL_BLANK.getCode())){
                judgeService.judgeFillBlank(event.getJudgeDTO(), submissionId);
            }
            if (event.getJudgeDTO().getQuestionType().equals(QuestionTypeEnum.COMPREHENSIVE.getCode())){
                judgeService.judgeComprehensive(event.getJudgeDTO(), submissionId);
            }

            // 发送判题完成状态
            JudgeHandler.sendJudgeStatus(submissionId, JudgeMessageConstants.FINISHED);
        } catch (Exception e) {
            log.error("判题失败", e);
            JudgeHandler.sendJudgeStatus(submissionId, JudgeMessageConstants.ERROR);
        }
    }
}
